﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Evpo.ContactData.ViewModel;
using System.Web.Configuration;
using Evpo.ContactData.Common;

namespace Evpo.ContactData.UI
{
    public class Global : System.Web.HttpApplication
    {

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(SiteMap_SiteMapResolve);
        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            Session[SessionStateKeys.Connection] =
                (new ModelFactory()).CreateConnection(
                    WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.
            IConnection conn = (IConnection)Session[SessionStateKeys.Connection];
            conn.Close();
        }

        private SiteMapNode SiteMap_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            SiteMapNode leaf = SiteMap.CurrentNode.Clone(true);

            string id = e.Context.Request.QueryString["ID"];

            if (String.IsNullOrEmpty(id))
            {
                id = e.Context.Request.QueryString["ContactID"];
            }

            SiteMapNode node = leaf;

            while (node != null && !node.Key.Contains(typeof(ContactSummary).Name.ToString().ToLower() + ".aspx"))
            {
                node = node.ParentNode;
            }

            if (node != null)
            {
                if (String.IsNullOrEmpty(id))
                {
                    node.Url = String.Empty;
                }
                else
                {
                    node.Url += "?ID=" + id;
                }
            }

            return leaf;
        }

    }
}
